package cn.itsource.org.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.DepartmentService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private DepartmentMapper departmentMapper;
    
    
    
    @GetMapping("/deptTree")
    @ApiOperation(value = "查询部门无限树")
    public AjaxResult deptTree(){
        List<Department> all = departmentService.deptTree();
        return AjaxResult.createSuccess(all);
    }



    @GetMapping
    @ApiOperation(value = "查询所有的部门")
    public AjaxResult list(){
        List<Department> all = departmentService.findAll();
        return AjaxResult.createSuccess(all);
    }
    @PostMapping
    @ApiOperation(value = "新增修改部门，新增没有id，修改有id") //swagger API
    public AjaxResult save(@Valid @RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            //打印错误的堆栈信息
            e.printStackTrace();
            return AjaxResult.createError();
        }
    }

    @ApiOperation(value = "根据id删除部门对象") //swagger API
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){

        try {
            departmentService.delete(id);

            return AjaxResult.createSuccess();
        } catch (Exception e) {
            //打印错误的堆栈信息
            e.printStackTrace();
            return AjaxResult.createError();
        }

    }
    @PostMapping("/findPage")
    @ApiOperation(value = "分页查询部门")
    public PageList<Department> findPage(@RequestBody DepartmentQuery query){

        return departmentService.findPage(query);
    }
    
    @ApiOperation(value = "根据id批量删除对象") //swagger API
    @PostMapping("/move")
    public AjaxResult move(@RequestBody DepartmentQuery query){

        try {
//            Long[] ids = query.getIds();
//            for (Long id : ids) {
//                departmentMapper.deleteByPrimaryKey(id);
//            }
            departmentService.move(query);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            //打印错误的堆栈信息
            e.printStackTrace();
            return AjaxResult.createError();
        }

    }
}
